package com.isoftstone.util;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Iterator;
import java.util.UUID;

/**
 * 上传文件
 * 创建人：
 * 创建时间：
 * @version
 */
public class FileUpload {

	/*private static String[] allowFiles = new String[]{".rar", ".doc", ".docx", ".zip",
			".pdf", ".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp",
			".rm", ".rmvb", ".wmv", ".avi", ".mp3", ".mp4", ".3gp", ".mkv",".xls",".xlsx",".txt"};*/


	private static String[] allowFiles = new String[]{ ".doc", ".docx",
			".pdf", ".gif", ".png", ".jpg", ".jpeg", ".bmp"
			,".xls",".xlsx",".txt"};

    /**
     * 作者:wangjs
     * 日期:2016-06-03 02:21:02
     * 功能: 文件上传
     * @param file 上文的文件
     * @param filePath 文件路径
     * @return 文件全称,带扩展名
     *
     */

    public static String prodFileUpLoad(MultipartFile file, String filePath) throws IOException{

        String fileFullName = null;

        if (file.getOriginalFilename() != null && !file.getOriginalFilename().equals(""))
        {
            //文件全名
            //String originalFilename = file.getOriginalFilename();

            //重新生成的文件名字
            String fileNameup = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) ;

            //扩展名
            // String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            // 上传文件
             fileFullName = FileUpload.fileUp(file, filePath, fileNameup);
        }

        return fileFullName;
    }

	/**
	 * add by xwj
	 * 以随机文件名上传文件
	 * @param file
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
    public static String prodFileUploadByRandomFileName(MultipartFile file, String filePath) throws IOException {
		String extName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) ;

		if (file.getOriginalFilename().lastIndexOf(".") >= 0){
			extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		}
		String fileName = UuidUtil.get32UUID()+DateUtil.getDaysHour();																																								;
		copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
		return fileName+extName;
	}


	/**上传文件
	 * @param file 			//文件对象
	 * @param filePath		//上传路径
	 * @param fileName		//文件名
	 * @return  文件名
	 */
	public static String fileUp(MultipartFile file, String filePath, String fileName)throws IOException{
		String extName = ""; // 扩展名格式：

		if (file.getOriginalFilename().lastIndexOf(".") >= 0){
			extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		}

		copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");

		return fileName+extName;
	}
	
	/**
	 * 写文件到当前目录的upload目录中
	 * @param in
	 * @param dir
	 * @throws IOException
	 */
	private static String copyFile(InputStream in, String dir, String realName)
			throws IOException {
		File file = mkdirsmy(dir,realName);
		FileUtils.copyInputStreamToFile(in, file);
		return realName;
	}
	
	
	/**判断路径是否存在，否：创建此路径
	 * @param dir  文件路径
	 * @param realName  文件名
	 * @throws IOException 
	 */
	public static File mkdirsmy(String dir, String realName) throws IOException{
		File file = new File(dir, realName);
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			file.createNewFile();
		}
		return file;
	}
	
	
	/**下载网络图片上传到服务器上
	 * @param httpUrl 图片网络地址
	 * @param filePath	图片保存路径
	 * @param myFileName  图片文件名(null时用网络图片原名)
	 * @return	返回图片名称
	 */
	public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
		
		URL url;						//定义URL对象url
		BufferedInputStream in;			//定义输入字节缓冲流对象in
		FileOutputStream file;			//定义文件输出流对象file
		try {
			String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
			url = new URL(httpUrl);		//初始化url对象
			in = new BufferedInputStream(url.openStream());									//初始化in对象，也就是获得url字节流
			//file = new FileOutputStream(new File(filePath +"\\"+ fileName));
			file = new FileOutputStream(mkdirsmy(filePath,fileName));
			int t;
			while ((t = in.read()) != -1) {
				file.write(t);
			}
			file.close();
			in.close();
			return fileName;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}



	/**
	 * 验证上传后缀
	 * @param fileName
	 * @return
	 */
	public static boolean checkFileType(String fileName) {
		Iterator type = Arrays.asList(allowFiles).iterator();
		while(type.hasNext()) {
			String ext = (String)type.next();
			if(fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}
}
